"""
天眼查cookie——acw_sc__v2检查算法
日期：2021-05-25
"""
import re


def get_hexxor(arg1):
    str_buffer = ''
    xor_param = "3000176000856006061501533003690027800375"
    arg_len = len(xor_param) if len(xor_param) <= len(arg1) else len(arg1)
    for i in range(arg_len):
        if i % 2 != 0:
            continue
        xor1 = int(xor_param[i: i + 2], 16)
        xor2 = int(arg1[i: i + 2], 16)
        res = hex(xor1 ^ xor2)[2:]
        if len(res) == 1:
            res = '0' + res
        str_buffer += res
    return str_buffer


def get_unsbox(arg1):
    box_list = [15, 35, 29, 24, 33, 16, 1, 38, 10, 9, 19, 31, 40, 27, 22, 23, 25, 13, 6, 11, 39, 18, 20, 8, 14, 21,
                32, 26, 2, 30, 7, 4, 17, 5, 3, 28, 34, 37, 12, 36]
    list_buffer = ['*' for i in range(len(box_list))]
    for i in range(len(arg1)):
        tmp = arg1[i]
        for j in range(len(box_list)):
            if box_list[j] == (i + 1):
                list_buffer[j] = tmp
    res = "".join(list_buffer)
    return res


def get_acw_sc__v2(arg1):
    return get_hexxor(get_unsbox(arg1))


def replace_cookie(arg1):
    acw_sc__v2 = get_acw_sc__v2(arg1=arg1)
    print(acw_sc__v2)
    with open('./tyc_login_yanzheng/tyc_cookie', 'r', encoding='utf8') as fp:
        cookie = fp.read()
        if cookie.__contains__('acw_sc__v2'):
            old_acw_sc__v2 = re.search(r'acw_sc__v2=(.*);?', cookie).group(1)
            new_cookie = cookie.replace(old_acw_sc__v2, acw_sc__v2)
        else:
            new_cookie = cookie + f'; acw_sc__v2={acw_sc__v2}'
    with open('./tyc_login_yanzheng/tyc_cookie', 'w', encoding='utf8') as fp:
        print(new_cookie)
        fp.write(new_cookie)



if __name__ == '__main__':
    # arg1 = '995A0EB547837E5C8274745C8409A2D3BE041389'
    # print(get_acw_sc__v2(arg1))
    print(get_acw_sc__v2(arg1))
